import axios from 'axios'
import qs from 'qs'
import router from '../router'
// 1.创建axios的实例
const instance = axios.create({
  baseURL: 'http://172.18.42.166:8188/admin/', // http://172.18.42.200:8080/admin/  //虚拟机地址：http://172.18.42.166:8188/admin/
  timeout: 5000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})
// 2.axios拦截器
// 请求拦截 instance.interceptors.request.use()
instance.interceptors.request.use(
  config => {
    config.headers.Authorization = window.sessionStorage.getItem('token') // 必须在请求头中使用 `Authorization` 字段提供 `token` 令牌
    config.data = qs.stringify(config.data) // 转为formdata数据格式
    // config.withCredentials = true // 允许携带token ,这个是解决跨域产生的相关问题
    return config
  },
  err => {
    console.log(err)
    return Promise.reject(err)
  }
)
// 响应拦截
instance.interceptors.response.use(response => {
  console.log(response.data)
  // 前端拦截登录状态
  // if (response.data.meta.status === -1) {
  // location.href = '/login'
  // alert('权限错误，请重新登录！')
  // this.$message.error(response.data.meta.msg)
  // return router.push('/login')
  // }
  return response
}, err => {
  return Promise.resolve(err.response)
})
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get (url, params) {
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: params
    }).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

/**
* post方法，对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function post (url, data = {}) {
  console.log(data)
  return new Promise((resolve, reject) => {
    instance.post(url, data)
      .then(response => {
        // console.log('repponse=' + response)
        if (response.data.meta.status === -1) {
          this.$message.error(response.data.meta.msg)
          alert('权限错误，请重新登录！')
          router.push('/login')
        }
        resolve(response)
      })
      .catch(err => {
        reject(err)
      })
  })
}
